package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    /*用户管理实现类*/
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);

        //select * from t_checkitem limit 0,10
        Page<User> page = userDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<User> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public void add(User user, Integer[] menuIds) {
        String password = user.getPassword();
        if (password != null && !password.equals("") && password.length() > 0) {
            String encode = new BCryptPasswordEncoder().encode(password);
            user.setPassword(encode);
            userDao.add(user);
        }
        if (menuIds != null && menuIds.length > 0) {
            this.addUserAndRoleIds(user.getId(), menuIds);
        }
    }

    @Override
    public User findByUserId(Integer userId) {
        return userDao.findByUserId(userId);
    }

    @Override
    public void delete(Integer userId) {
        //先删中间表
        userDao.deleteCenterByUserId(userId);
        userDao.delete(userId);
    }

    @Override
    public void edit(User user, Integer[] menuIds) {
        userDao.update(user);
        if (menuIds != null && menuIds.length > 0) {
            //根据userid删除中间表
            Integer userId = user.getId();
            userDao.deleteCenterByUserId(userId);
            addUserAndRoleIds(userId, menuIds);
        }
    }

    @Override
    public Set<Integer> findRoleIds(Integer id) {
        return userDao.findRoleIds(id);
    }

    /*关联关系*/
    public void addUserAndRoleIds(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            Map map = new HashMap();
            for (Integer roleId : roleIds) {
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.addUserAndRoleIds(map);
            }
        }
    }

    @Override
    public User findByUserName(String username) {
        User user = userDao.findByUserName(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            //角色ID，去查询关联权限
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public List<Map<String, Object>> findUserMenu(Integer id) {
        //根据用户传入的id查询中间表，找到对应的角色id
        Integer roleId = roleDao.findByRole(id);

        //先根据父菜单找到子菜单，再根据父菜单的id拿到子菜单，放入父菜单的属性中

        List<Map<String, Object>> maps = menuDao.parentMenus(roleId);
        for (Map<String, Object> map : maps) {
            Integer parentId = (Integer) map.get("id");

            List<Map<String, String>> sonmaps = new ArrayList<>();
            sonmaps = menuDao.sonMenus(parentId);
            map.put("children", sonmaps);
        }
        return maps;

    }

}
